package chloroform

import java.lang.String
import java.io.{OutputStream, InputStream}
import java.net.{URLConnection, URL}

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Feb 20, 2011
 * Time: 6:24:58 PM
 */

@serializable @SerialVersionUID(1)
trait ResourceResolver {
  def resolve(resource: String): Resource
}

class ResourceNotFoundException(resource: String, cause: Throwable) extends Exception(resource, cause)

@serializable @SerialVersionUID(1)
trait Resource {
  def resourceName: String
  def openInputStream: InputStream
  def openOutputStream: OutputStream
}

@SerialVersionUID(1)
abstract class URLResourceResolver extends ResourceResolver {
  def resolve(resource: String) = {
    new URLResource(resolveURL(resource), resource)
  }

  def resolveURL(resource: String): URL
}

@SerialVersionUID(1)
class URLResource(url: URL, val resourceName: String) extends Resource {

  override def toString = url.toString

  def openOutputStream = {
    val connection: URLConnection = url.openConnection
    connection.setDoOutput(true)
    connection.getOutputStream
  }

  def openInputStream = {
    val connection: URLConnection = url.openConnection
    connection.setDoInput(true)
    connection.getInputStream
  }
}
